package com.klxedu.ms.gateway.event;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.goldgov.kcloud.core.message.KMessage;
import com.klxedu.ms.gateway.TenancyConfiguration;

@Component
public class EventSender {

	private final AmqpTemplate amqpTemplate;

	@Autowired
	public EventSender(AmqpTemplate amqpTemplate) {
		this.amqpTemplate = amqpTemplate;
	}
	
	public void send(Event event) {
		try {
			String message = new ObjectMapper().writeValueAsString(event);
			amqpTemplate.convertAndSend("userEventExchange","", convertToKMessage(message));
		} catch (Exception e) {
			Logger.getLogger(this.getClass()).error(e);
		}
	}
	
	private KMessage convertToKMessage(final String message) {
		return new KMessage(message).addTenancyHeader(TenancyConfiguration.getTenancy());
	}
	
}
